import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
} from '@nestjs/common';
import { WorkloadService } from './workload.service';
import { ResponseUtil } from '../common/utils/response.util';

@Controller('workload')
export class WorkloadController {
  constructor(private readonly workloadService: WorkloadService) {}

  //根据命名空间查询工作负载列表
  public workloadList: any = {
    list: [
      {
        kind: 'Deployment',
        namespace: 'karmada-system',
        name: 'karmada-webhook',
        status: 'Available',
        replicas: 1,
        readyReplicas: 1,
        availableReplicas: 1,
        images: ['docker.io/karmada/karmada-webhook:v1.8.0'],
        createTime: '2025-08-25 17:08:54',
      },
      {
        kind: 'Deployment',
        namespace: 'karmada-system',
        name: 'karmada-scheduler',
        status: 'Available',
        replicas: 1,
        readyReplicas: 1,
        availableReplicas: 1,
        images: ['docker.io/karmada/karmada-scheduler:v1.8.0'],
        createTime: '2025-08-25 17:08:49',
      },
      {
        kind: 'Deployment',
        namespace: 'karmada-system',
        name: 'karmada-dashboard-web',
        status: 'Available',
        replicas: 1,
        readyReplicas: 1,
        availableReplicas: 1,
        images: ['karmada/karmada-dashboard-web:main'],
        createTime: '2025-08-26 09:41:01',
      },
      {
        kind: 'Deployment',
        namespace: 'karmada-system',
        name: 'kube-controller-manager',
        status: 'Available',
        replicas: 1,
        readyReplicas: 1,
        availableReplicas: 1,
        images: ['registry.k8s.io/kube-controller-manager:v1.25.4'],
        createTime: '2025-08-25 17:08:47',
      },
      {
        kind: 'Deployment',
        namespace: 'karmada-system',
        name: 'karmada-apiserver',
        status: 'Available',
        replicas: 1,
        readyReplicas: 1,
        availableReplicas: 1,
        images: ['registry.k8s.io/kube-apiserver:v1.25.4'],
        createTime: '2025-08-25 17:08:11',
      },
      {
        kind: 'Deployment',
        namespace: 'karmada-system',
        name: 'karmada-controller-manager',
        status: 'Available',
        replicas: 1,
        readyReplicas: 1,
        availableReplicas: 1,
        images: ['docker.io/karmada/karmada-controller-manager:v1.8.0'],
        createTime: '2025-08-25 17:08:52',
      },
      {
        kind: 'Deployment',
        namespace: 'karmada-system',
        name: 'karmada-dashboard-api',
        status: 'Available',
        replicas: 1,
        readyReplicas: 1,
        availableReplicas: 1,
        images: ['karmada/karmada-dashboard-api:main'],
        createTime: '2025-08-26 09:41:01',
      },
      {
        kind: 'Deployment',
        namespace: 'karmada-system',
        name: 'karmada-aggregated-apiserver',
        status: 'Available',
        replicas: 1,
        readyReplicas: 1,
        availableReplicas: 1,
        images: ['docker.io/karmada/karmada-aggregated-apiserver:v1.8.0'],
        createTime: '2025-08-25 17:08:42',
      },
      {
        kind: 'StatefulSet',
        namespace: 'karmada-system',
        name: 'etcd',
        status: 'Available',
        replicas: 1,
        readyReplicas: 1,
        availableReplicas: null,
        images: ['registry.k8s.io/etcd:3.5.9-0'],
        createTime: '2025-08-25 17:08:09',
      },
    ],
    continueToken: null,
  };
  @Post('/listByNamespace/:agentId')
  public listByNamespace() {
    return ResponseUtil.success(this.workloadList);
  }

  // 获取工作负载yaml文件
  public workloadYaml: any = {
    apiVersion: 'apps/v1',
    kind: 'Deployment',
    metadata: {
      annotations: {
        'deployment.kubernetes.io/revision': '1',
      },
      creationTimestamp: {
        dateTime: {
          date: {
            year: 2025,
            month: 8,
            day: 25,
          },
          time: {
            hour: 9,
            minute: 8,
            second: 54,
            nano: 0,
          },
        },
        offset: {
          totalSeconds: 0,
        },
      },
      generation: 1,
      labels: {
        'karmada.io/bootstrapping': 'app-defaults',
      },
      managedFields: [
        {
          apiVersion: 'apps/v1',
          fieldsType: 'FieldsV1',
          fieldsV1: {
            'f:metadata': {
              'f:labels': {
                '.': {},
                'f:karmada.io/bootstrapping': {},
              },
            },
            'f:spec': {
              'f:progressDeadlineSeconds': {},
              'f:replicas': {},
              'f:revisionHistoryLimit': {},
              'f:selector': {},
              'f:strategy': {
                'f:rollingUpdate': {
                  '.': {},
                  'f:maxSurge': {},
                  'f:maxUnavailable': {},
                },
                'f:type': {},
              },
              'f:template': {
                'f:metadata': {
                  'f:labels': {
                    '.': {},
                    'f:app': {},
                  },
                  'f:name': {},
                  'f:namespace': {},
                },
                'f:spec': {
                  'f:affinity': {
                    '.': {},
                    'f:podAntiAffinity': {
                      '.': {},
                      'f:requiredDuringSchedulingIgnoredDuringExecution': {},
                    },
                  },
                  'f:automountServiceAccountToken': {},
                  'f:containers': {
                    'k:{"name":"karmada-webhook"}': {
                      '.': {},
                      'f:command': {},
                      'f:image': {},
                      'f:imagePullPolicy': {},
                      'f:name': {},
                      'f:ports': {
                        '.': {},
                        'k:{"containerPort":8443,"protocol":"TCP"}': {
                          '.': {},
                          'f:containerPort': {},
                          'f:name': {},
                          'f:protocol': {},
                        },
                      },
                      'f:readinessProbe': {
                        '.': {},
                        'f:failureThreshold': {},
                        'f:httpGet': {
                          '.': {},
                          'f:path': {},
                          'f:port': {},
                          'f:scheme': {},
                        },
                        'f:periodSeconds': {},
                        'f:successThreshold': {},
                        'f:timeoutSeconds': {},
                      },
                      'f:resources': {},
                      'f:terminationMessagePath': {},
                      'f:terminationMessagePolicy': {},
                      'f:volumeMounts': {
                        '.': {},
                        'k:{"mountPath":"/etc/kubeconfig"}': {
                          '.': {},
                          'f:mountPath': {},
                          'f:name': {},
                          'f:readOnly': {},
                          'f:subPath': {},
                        },
                        'k:{"mountPath":"/var/serving-cert"}': {
                          '.': {},
                          'f:mountPath': {},
                          'f:name': {},
                          'f:readOnly': {},
                        },
                      },
                    },
                  },
                  'f:dnsPolicy': {},
                  'f:restartPolicy': {},
                  'f:schedulerName': {},
                  'f:securityContext': {},
                  'f:terminationGracePeriodSeconds': {},
                  'f:tolerations': {},
                  'f:volumes': {
                    '.': {},
                    'k:{"name":"karmada-webhook-cert"}': {
                      '.': {},
                      'f:name': {},
                      'f:secret': {
                        '.': {},
                        'f:defaultMode': {},
                        'f:secretName': {},
                      },
                    },
                    'k:{"name":"kubeconfig"}': {
                      '.': {},
                      'f:name': {},
                      'f:secret': {
                        '.': {},
                        'f:defaultMode': {},
                        'f:secretName': {},
                      },
                    },
                  },
                },
              },
            },
          },
          manager: 'karmadactl',
          operation: 'Update',
          time: {
            dateTime: {
              date: {
                year: 2025,
                month: 8,
                day: 25,
              },
              time: {
                hour: 9,
                minute: 8,
                second: 54,
                nano: 0,
              },
            },
            offset: {
              totalSeconds: 0,
            },
          },
        },
        {
          apiVersion: 'apps/v1',
          fieldsType: 'FieldsV1',
          fieldsV1: {
            'f:metadata': {
              'f:annotations': {
                '.': {},
                'f:deployment.kubernetes.io/revision': {},
              },
            },
            'f:status': {
              'f:availableReplicas': {},
              'f:conditions': {
                '.': {},
                'k:{"type":"Available"}': {
                  '.': {},
                  'f:lastTransitionTime': {},
                  'f:lastUpdateTime': {},
                  'f:message': {},
                  'f:reason': {},
                  'f:status': {},
                  'f:type': {},
                },
                'k:{"type":"Progressing"}': {
                  '.': {},
                  'f:lastTransitionTime': {},
                  'f:lastUpdateTime': {},
                  'f:message': {},
                  'f:reason': {},
                  'f:status': {},
                  'f:type': {},
                },
              },
              'f:observedGeneration': {},
              'f:readyReplicas': {},
              'f:replicas': {},
              'f:updatedReplicas': {},
            },
          },
          manager: 'k3s',
          operation: 'Update',
          subresource: 'status',
          time: {
            dateTime: {
              date: {
                year: 2025,
                month: 8,
                day: 28,
              },
              time: {
                hour: 1,
                minute: 45,
                second: 31,
                nano: 0,
              },
            },
            offset: {
              totalSeconds: 0,
            },
          },
        },
      ],
      name: 'karmada-webhook',
      namespace: 'karmada-system',
      resourceVersion: '48660',
      uid: 'da931f8d-11b4-4875-92db-63c4099e6704',
    },
    spec: {
      progressDeadlineSeconds: 600,
      replicas: 1,
      revisionHistoryLimit: 10,
      selector: {
        matchLabels: {
          app: 'karmada-webhook',
        },
      },
      strategy: {
        rollingUpdate: {
          maxSurge: '25%',
          maxUnavailable: '25%',
        },
        type: 'RollingUpdate',
      },
      template: {
        metadata: {
          labels: {
            app: 'karmada-webhook',
          },
          name: 'karmada-webhook',
          namespace: 'karmada-system',
        },
        spec: {
          affinity: {
            podAntiAffinity: {
              requiredDuringSchedulingIgnoredDuringExecution: [
                {
                  labelSelector: {
                    matchExpressions: [
                      {
                        key: 'app',
                        operator: 'In',
                        values: ['karmada-webhook'],
                      },
                    ],
                  },
                  topologyKey: 'kubernetes.io/hostname',
                },
              ],
            },
          },
          automountServiceAccountToken: false,
          containers: [
            {
              command: [
                '/bin/karmada-webhook',
                '--kubeconfig=/etc/kubeconfig',
                '--bind-address=0.0.0.0',
                '--secure-port=8443',
                '--cert-dir=/var/serving-cert',
                '--v=4',
              ],
              image: 'docker.io/karmada/karmada-webhook:v1.8.0',
              imagePullPolicy: 'IfNotPresent',
              name: 'karmada-webhook',
              ports: [
                {
                  containerPort: 8443,
                  name: 'webhook',
                  protocol: 'TCP',
                },
              ],
              readinessProbe: {
                failureThreshold: 3,
                httpGet: {
                  path: '/readyz',
                  port: 8443,
                  scheme: 'HTTPS',
                },
                periodSeconds: 10,
                successThreshold: 1,
                timeoutSeconds: 1,
              },
              resources: {},
              terminationMessagePath: '/dev/termination-log',
              terminationMessagePolicy: 'File',
              volumeMounts: [
                {
                  mountPath: '/etc/kubeconfig',
                  name: 'kubeconfig',
                  readOnly: true,
                  subPath: 'kubeconfig',
                },
                {
                  mountPath: '/var/serving-cert',
                  name: 'karmada-webhook-cert',
                  readOnly: true,
                },
              ],
            },
          ],
          dnsPolicy: 'ClusterFirst',
          restartPolicy: 'Always',
          schedulerName: 'default-scheduler',
          securityContext: {},
          terminationGracePeriodSeconds: 30,
          tolerations: [
            {
              effect: 'NoExecute',
              operator: 'Exists',
            },
          ],
          volumes: [
            {
              name: 'kubeconfig',
              secret: {
                defaultMode: 420,
                secretName: 'kubeconfig',
              },
            },
            {
              name: 'karmada-webhook-cert',
              secret: {
                defaultMode: 420,
                secretName: 'karmada-webhook-cert',
              },
            },
          ],
        },
      },
    },
    status: {
      availableReplicas: 1,
      conditions: [
        {
          lastTransitionTime: {
            dateTime: {
              date: {
                year: 2025,
                month: 8,
                day: 25,
              },
              time: {
                hour: 9,
                minute: 8,
                second: 54,
                nano: 0,
              },
            },
            offset: {
              totalSeconds: 0,
            },
          },
          lastUpdateTime: {
            dateTime: {
              date: {
                year: 2025,
                month: 8,
                day: 25,
              },
              time: {
                hour: 9,
                minute: 8,
                second: 55,
                nano: 0,
              },
            },
            offset: {
              totalSeconds: 0,
            },
          },
          message:
            'ReplicaSet "karmada-webhook-67f6f4db8" has successfully progressed.',
          reason: 'NewReplicaSetAvailable',
          status: 'True',
          type: 'Progressing',
        },
        {
          lastTransitionTime: {
            dateTime: {
              date: {
                year: 2025,
                month: 8,
                day: 28,
              },
              time: {
                hour: 1,
                minute: 45,
                second: 31,
                nano: 0,
              },
            },
            offset: {
              totalSeconds: 0,
            },
          },
          lastUpdateTime: {
            dateTime: {
              date: {
                year: 2025,
                month: 8,
                day: 28,
              },
              time: {
                hour: 1,
                minute: 45,
                second: 31,
                nano: 0,
              },
            },
            offset: {
              totalSeconds: 0,
            },
          },
          message: 'Deployment has minimum availability.',
          reason: 'MinimumReplicasAvailable',
          status: 'True',
          type: 'Available',
        },
      ],
      observedGeneration: 1,
      readyReplicas: 1,
      replicas: 1,
      updatedReplicas: 1,
    },
  };
  @Post('/get/:agentId')
  postWorkloadYaml(@Body() body: any) {
    return ResponseUtil.success(this.workloadYaml, '查询成功');
  }

  // 删除当前工作负载
  @Post('/delete/:agentId')
  postDeleteWorkload(@Body() body: any) {
    const currentIndex = this.workloadList.list.findIndex(
      (item) => item.name === body.name,
    );
    this.workloadList.list.splice(currentIndex, 1);
    return ResponseUtil.success(null, '删除成功');
  }

  public workloadDetail: any = {
    replicaSets: [
      {
        name: 'nginx-deployment-66b6c48dd5',
        desired: '3',
        current: '3',
        ready: '2',
        createTime: '2025-08-25T09:02:55Z',
        imageLabels: ['nginx:1.23.3'],
        pods: [
          {
            podName: 'nginx-deployment-66b6c48dd5-2xq7k',
            podIp: '10.240.0.61',
            hostIp: '192.168.8.31',
            status: 'Ready',
            createTime: '2025-08-25T09:10:23Z',
            restartCount: 0,
            nodeName: 'worker-node-1',
          },
          {
            podName: 'nginx-deployment-66b6c48dd5-5rklm',
            podIp: '10.240.0.62',
            hostIp: '192.168.8.32',
            status: 'Ready',
            createTime: '2025-08-25T09:10:25Z',
            restartCount: 0,
            nodeName: 'worker-node-2',
          },
          {
            podName: 'nginx-deployment-66b6c48dd5-9tgjf',
            podIp: '10.240.0.63',
            hostIp: '192.168.8.33',
            status: 'Pending',
            createTime: '2025-08-25T09:10:27Z',
            restartCount: 1,
            nodeName: 'worker-node-3',
            reason: 'ContainerCreating',
          },
        ],
        age: '3d5h',
        labels: {
          app: 'nginx',
          'pod-template-hash': '66b6c48dd5',
        },
      },
      {
        name: 'redis-cluster-7f9d654b8',
        desired: '6',
        current: '5',
        ready: '4',
        imageLabels: ['redis:6.2.7-alpine'],
        createTime: '2025-08-25T09:02:55Z',
        pods: [
          {
            podName: 'redis-cluster-7f9d654b8-2c7vj',
            podIp: '10.240.0.71',
            hostIp: '192.168.8.31',
            status: 'Ready',
            createTime: '2025-08-24T14:30:12Z',
            restartCount: 0,
            nodeName: 'worker-node-1',
          },
          {
            podName: 'redis-cluster-7f9d654b8-5mz8k',
            podIp: '10.240.0.72',
            hostIp: '192.168.8.32',
            status: 'Ready',
            createTime: '2025-08-24T14:30:15Z',
            restartCount: 0,
            nodeName: 'worker-node-2',
          },
          {
            podName: 'redis-cluster-7f9d654b8-7q4zt',
            podIp: '10.240.0.73',
            hostIp: '192.168.8.33',
            status: 'Running',
            createTime: '2025-08-24T14:30:18Z',
            restartCount: 2,
            nodeName: 'worker-node-3',
          },
          {
            podName: 'redis-cluster-7f9d654b8-dkf2p',
            podIp: '10.240.0.74',
            hostIp: '192.168.8.34',
            status: 'Ready',
            createTime: '2025-08-24T14:30:21Z',
            restartCount: 0,
            nodeName: 'worker-node-4',
          },
          {
            podName: 'redis-cluster-7f9d654b8-fx7bm',
            podIp: '10.240.0.75',
            hostIp: '192.168.8.35',
            status: 'Terminating',
            createTime: '2025-08-24T14:30:24Z',
            restartCount: 1,
            nodeName: 'worker-node-5',
            reason: 'ScaleDown',
          },
        ],
        age: '1d12h',
        labels: {
          app: 'redis',
          cluster: 'redis-cluster',
          'pod-template-hash': '7f9d654b8',
        },
      },
      {
        name: 'api-service-55b9f7c6d',
        desired: '2',
        current: '2',
        ready: '2',
        imageLabels: ['mycompany/api-service:v2.3.1', 'busybox:1.35.0'],
        createTime: '2025-08-25T09:02:55Z',
        pods: [
          {
            podName: 'api-service-55b9f7c6d-jk2p7',
            podIp: '10.240.0.81',
            hostIp: '192.168.8.32',
            status: 'Ready',
            createTime: '2025-08-26T08:45:33Z',
            restartCount: 0,
            nodeName: 'worker-node-2',
            resources: {
              cpu: '500m',
              memory: '512Mi',
            },
          },
          {
            podName: 'api-service-55b9f7c6d-tg8w3',
            podIp: '10.240.0.82',
            hostIp: '192.168.8.34',
            status: 'Ready',
            createTime: '2025-08-26T08:45:36Z',
            restartCount: 0,
            nodeName: 'worker-node-4',
            resources: {
              cpu: '500m',
              memory: '512Mi',
            },
          },
        ],
        age: '5h20m',
        labels: {
          app: 'api-service',
          version: 'v2',
          'pod-template-hash': '55b9f7c6d',
        },
      },
      {
        name: 'local-path-provisioner-7b7dc8d6f5',
        desired: '1',
        current: '1',
        ready: '1',
        imageLabels: ['rancher/local-path-provisioner:v0.0.21'],
        createTime: '2025-08-25T09:02:55Z',
        pods: [
          {
            podName: 'local-path-provisioner-7b7dc8d6f5-kfzh7',
            podIp: '10.240.0.58',
            hostIp: '192.168.8.30',
            status: 'Ready',
            createTime: '2025-08-25T09:02:56Z',
            restartCount: 0,
            nodeName: 'master-node-1',
          },
        ],
        age: '4d2h',
        labels: {
          app: 'local-path-provisioner',
          'pod-template-hash': '7b7dc8d6f5',
        },
      },
    ],
  };

  /* 获取工作负载详情 */
  @Post('/get/detail/:agentId')
  postGetWorkloadDetail(@Body() body: any) {
    return ResponseUtil.success(this.workloadDetail, '查询成功');
  }

  /* 获取副本集yaml */
  public replicaSetYaml: any = {
    kind: 'ReplicaSet',
    metadata: {
      annotations: {
        'deployment.kubernetes.io/desired-replicas': '3',
        'deployment.kubernetes.io/max-replicas': '4',
        'objectset.rio.cattle.io/id': '',
        'objectset.rio.cattle.io/owner-gvk': 'k3s.cattle.io/v1, Kind=Addon',
        'objectset.rio.cattle.io/owner-name': 'local-storage',
        'objectset.rio.cattle.io/owner-namespace': 'kube-system',
      },
      labels: {
        app: 'local-path-provisioner',
        'pod-template-hash': '7b7dc8d6f5',
      },
      name: 'local-path-provisioner-7b7dc8d6f5',
      namespace: 'kube-system',
      ownerReferences: [
        {
          apiVersion: 'apps/v1',
          blockOwnerDeletion: true,
          controller: true,
          kind: 'Deployment',
          name: 'local-path-provisioner',
          uid: '6166dd11-128a-4f2c-b9e2-deb73ac25afa',
        },
      ],
      resourceVersion: '338252',
    },
    spec: {
      replicas: 3,
      selector: {
        matchLabels: {
          app: 'local-path-provisioner',
          'pod-template-hash': '7b7dc8d6f5',
        },
      },
      template: {
        metadata: {
          creationTimestamp: null,
          labels: {
            app: 'local-path-provisioner',
            'pod-template-hash': '7b7dc8d6f5',
          },
        },
        spec: {
          containers: [
            {
              command: [
                'local-path-provisioner',
                'start',
                '--config',
                '/etc/config/config.json',
              ],
              env: [
                {
                  name: 'POD_NAMESPACE',
                  valueFrom: {
                    fieldRef: {
                      apiVersion: 'v1',
                      fieldPath: 'metadata.namespace',
                    },
                  },
                },
              ],
              image: 'rancher/local-path-provisioner:v0.0.21',
              imagePullPolicy: 'IfNotPresent',
              name: 'local-path-provisioner',
              resources: {},
              terminationMessagePath: '/dev/termination-log',
              terminationMessagePolicy: 'File',
              volumeMounts: [
                {
                  mountPath: '/etc/config/',
                  name: 'config-volume',
                },
              ],
            },
          ],
          dnsPolicy: 'ClusterFirst',
          priorityClassName: 'system-node-critical',
          restartPolicy: 'Always',
          schedulerName: 'default-scheduler',
          securityContext: {},
          serviceAccount: 'local-path-provisioner-service-account',
          serviceAccountName: 'local-path-provisioner-service-account',
          terminationGracePeriodSeconds: 30,
          tolerations: [
            {
              key: 'CriticalAddonsOnly',
              operator: 'Exists',
            },
            {
              effect: 'NoSchedule',
              key: 'node-role.kubernetes.io/control-plane',
              operator: 'Exists',
            },
            {
              effect: 'NoSchedule',
              key: 'node-role.kubernetes.io/master',
              operator: 'Exists',
            },
          ],
          volumes: [
            {
              configMap: {
                defaultMode: 420,
                name: 'local-path-config',
              },
              name: 'config-volume',
            },
          ],
        },
      },
    },
    status: {
      availableReplicas: 3,
      fullyLabeledReplicas: 3,
      observedGeneration: 17,
      readyReplicas: 3,
      replicas: 3,
    },
  };
  @Post('/get/replicaSet/:agentId')
  postGetReplicaSetYaml(@Body() body: any) {
    return ResponseUtil.success(this.replicaSetYaml, '查询成功');
  }


  /* 更新更新策略 */
  @Post('/edit/updateStrategy/:agentId')
  postUpdateUpdateStrategy(@Body() body: any) {
    return ResponseUtil.success(null, '更新成功');
  }


  /* 扩容伸缩 */
  @Post('/update/replicaSet/:agentId')
  postScale(@Body() body: any) {
    return ResponseUtil.success(null, '扩容成功');
  }
}
